﻿using netaddICTs.Umb.ProtectedMedia.Business.IO;

using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.media;

namespace netaddICTs.Umb.ProtectedMedia.Business.EventHandlers {
    
    /// <summary>
    /// Handles deletion of physical files (Only 'Protected Files')
    /// </summary>
    public class DeletePhysicalFile : ApplicationBase {
        
        public DeletePhysicalFile(){
            Media.BeforeDelete += OnMediaBeforeDelete;
        }

        /// <summary>
        /// Handles the BeforeDelete event on media items
        /// Deletes physical file from storage if type of media item is 'Protected File'
        /// </summary>
        /// <param name="sender">Media item that fires the event</param>
        /// <param name="e">An instance of <see cref="DeleteEventArgs"/>DeleteEventArgs</param>
        private static void OnMediaBeforeDelete(Media sender, DeleteEventArgs e) {

            //umbraco framework takes care of firing events for child objects, so no need to check for folders, we just need to take care of actual deletion of the protected file.
            if (string.Compare(sender.ContentType.Alias, Configuration.ProtectedMedia.Instance.Aliases.ProtectedFileAlias.UmbracoAlias, true) == 0)
                FileStorageFactory.GetFileStorageImplementation().Delete(sender.Id);
        }
    }
}
